package com.shetuan.servelt;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shetuan.bean.*;
import com.shetuan.dao.*;

/**
 * 所有的注册servlet
 * * @author Administrator
 */
public class RegistServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        LoginDao logindao = new LoginDao();
        MemberDao memberDao = new MemberDao();
        CommunityDao communitydao = new CommunityDao();
        Object ope = request.getParameter("ope");
        System.out.println("registServlet" + ope);

        if (ope.equals("manager")) {
            /**
             * LoginRegist
             */
            String username = request.getParameter("username");
            String userpass = request.getParameter("userpass");
            String managerId = request.getParameter("power");

            String userrealname = request.getParameter("userrealname");
            String usergender = request.getParameter("usergender");
            String useremail = request.getParameter("email");
            String userphone = request.getParameter("phone");
            String usergrade = request.getParameter("usergrade");
            String userinstitute = request.getParameter("userinstitute");
            String useradd = request.getParameter("useradd");

            if(username == null || username.isEmpty() || userpass == null || userpass.isEmpty()){
                request.getRequestDispatcher("admin/manager_add.jsp?rs=incomplete").forward(request, response);
                return;
            }

            Login login = new Login();
            login.setLoginName(username);
            login.setLoginPass(userpass);
            if(managerId == null){
                managerId = "0";
            }
            login.setManagerId(Integer.parseInt(managerId));

            System.out.println(username+ " " + userpass+ " " +managerId);
            String judge = "";

            // 根据用户类型（managerId）决定调用哪个DAO方法
            if ("0".equals(managerId)) {
                // 添加普通成员，需要创建Member信息
                Member member = new Member();
                member.setMemberName(userrealname);
                member.setMemberGender(usergender);
                member.setMemberEmail(useremail);
                member.setMemberPhone(userphone);
                member.setMemberGrade(usergrade);
                member.setMemberInstitute(userinstitute);
                member.setMemberAdd(useradd);
                // 此方法会创建Login和Member，但会将managerId设为0
                judge = memberDao.addIndexLogin(login, member);
            } else {
                // 添加管理员（1或2），只需要创建Login信息
                // 此方法只创建Login，并保留设置的managerId
                judge = logindao.addLogin(login);
            }

            if (judge.equals("success")) {
                System.out.println("登录成功");
                request.getRequestDispatcher("admin/manager_add.jsp?rs=success").forward(request, response);
            } else if (judge.equals("exist")) {
                request.getRequestDispatcher("admin/manager_add.jsp?rs=exist").forward(request, response);
            } else {
                request.getRequestDispatcher("admin/manager_add.jsp?rs=fail").forward(request, response);
            }
        } else if (ope.equals("index")) {
            /**
             * IndexRegist
             */
            String username = request.getParameter("username");
            String userrealname = request.getParameter("userrealname");
            String userpass = request.getParameter("userpass");
            String repass = request.getParameter("repass");
            String usergender = request.getParameter("usergender");
            String useremail = request.getParameter("email");
            String userphone = request.getParameter("phone");
            String usergrade = request.getParameter("usergrade");
            String userinstitute = request.getParameter("userinstitute");
            String useradd = request.getParameter("useradd");

            if (username == null || username.isEmpty() || userrealname == null || userrealname.isEmpty()
                    || userpass == null || userpass.isEmpty() || repass == null || repass.isEmpty()
                    || usergender == null || usergender.isEmpty() || useremail == null || useremail.isEmpty()
                    || userphone == null || userphone.isEmpty() || usergrade == null || usergrade.isEmpty()
                    || userinstitute == null || userinstitute.isEmpty() || useradd == null || useradd.isEmpty()) {
                request.getRequestDispatcher("regist.jsp?rs=incomplete").forward(request, response);
                return;
            }

            Login login = new Login();
            login.setLoginName(username);
            login.setLoginPass(userpass);
            Member member = new Member();
            member.setMemberName(userrealname);
            member.setMemberGender(usergender);
            member.setMemberEmail(useremail);
            member.setMemberPhone(userphone);
            member.setMemberGrade(usergrade);
            member.setMemberInstitute(userinstitute);
            member.setMemberAdd(useradd);
            String judge = memberDao.addIndexLogin(login, member);
            if (judge.equals("success")) {
                System.out.println("注册成功");
                request.getRequestDispatcher("regist.jsp?rs=success").forward(request, response);
            } else if (judge.equals("exist")) {
                request.getRequestDispatcher("regist.jsp?rs=exist").forward(request, response);
            } else {
                request.getRequestDispatcher("regist.jsp?rs=fail").forward(request, response);
            }

        } else if (ope.equals("community")) {
            /**
             * CommunityRegist
             */
            //当获取到当前登录用户的信息后，倘若managerId不为1，则拒绝添加社团，并提示您没有权限访问此页面，请使用系统管理员账户登录！
            Login login = (Login) request.getSession().getAttribute("login");
            if (login == null || login.getManagerId() != 1) {
                request.setAttribute("errorMsg", "您没有权限添加社团，请使用系统管理员账户登录！");
                request.getRequestDispatcher("error.jsp").forward(request, response);
                return;
            }

            String cname = request.getParameter("communityName");
            String crname = request.getParameter("createrName");

            String createrId = memberDao.getLoginNameByName(crname);
            /*System.out.println(crname+"and"+createrId);*/
            if (createrId == null) {
                System.out.println("创建者 " + crname );
                request.getRequestDispatcher("admin/community_add.jsp?rs=mNotIn").forward(request, response);
            } else {
                String crdate = request.getParameter("createDate");

                // [MODIFIED] 添加 null 和 empty 检查，防止 NumberFormatException
                String csumStr = request.getParameter("communityNum");
                int csum = (csumStr != null && !csumStr.isEmpty()) ? Integer.parseInt(csumStr) : 0;

                String crange = request.getParameter("communityRange");

                // [MODIFIED] 添加 null 和 empty 检查，防止 NumberFormatException
                String cclassStr = request.getParameter("communityClass");
                int cclass = (cclassStr != null && !cclassStr.isEmpty()) ? Integer.parseInt(cclassStr) : 0;

                String cInfo = request.getParameter("communityInfo");

                // [MODIFIED] 添加 null 和 empty 检查，防止 NumberFormatException
                String isCreateStr = request.getParameter("isCreate");
                int isCreate = (isCreateStr != null && !isCreateStr.isEmpty()) ? Integer.parseInt(isCreateStr) : 0;


                Community community = new Community();
                community.setCommunityName(cname);
                community.setCommunityCreaterId(createrId);
                community.setCommunityCreaterName(crname);
                community.setCommunityCreateDate(crdate);
                community.setCommunityNum(csum);
                community.setCommunityRange(crange);
                community.setCommunityClassId(cclass);
                community.setCommunityInfo(cInfo);
                community.setCommunityCreate(isCreate);
                /*System.out.println("hahahah");*/
                String judge = communitydao.addAdminCommunity(community);
                if (judge.equals("success")) {
                    System.out.println("创建成功");
                    request.getRequestDispatcher("admin/community_add.jsp?rs=success").forward(request, response);
                } else if (judge.equals("exist")) {
                    request.getRequestDispatcher("admin/community_add.jsp?rs=exist").forward(request, response);
                } else {
                    request.getRequestDispatcher("admin/community_add.jsp?rs=fail").forward(request, response);
                }
            }
        } else if (ope.equals("activity")) {
            /**
             * ActivityRegist
             */
            CommunityDao communityDao = new CommunityDao();
            String cname = request.getParameter("communityName");
            int cid = communityDao.getCommunityIdByCName(cname);
            if (cid == 0) {
                request.getRequestDispatcher("admin/activity_add.jsp?rs=mNotIn").forward(request, response);
            } else {
                Activity activity = new Activity();
                ActivityDao activityDao = new ActivityDao();
                activity.setActivityName(request.getParameter("activityName"));
                activity.setActivityId(0);
                activity.setCommunityName(cname);
                activity.setCommunityId(cid);
                activity.setActivityDate(request.getParameter("activityDate"));
                activity.setActivityPlace(request.getParameter("activityPlace"));
                //
                // *** 这是修改后的代码 ***
                //
                activity.setActivityInfo(request.getParameter("activityInfo"));
                //
                // *** 这是修改后的代码 ***
                //
                String judge = activityDao.addAdminActivity(activity);
                if (judge.equals("success")) {
                    System.out.println("创建成功");
                    request.getRequestDispatcher("admin/activity_add.jsp?rs=success").forward(request, response);
                } else if (judge.equals("exist")) {
                    request.getRequestDispatcher("admin/activity_add.jsp?rs=exist").forward(request, response);
                } else {
                    request.getRequestDispatcher("admin/activity_add.jsp?rs=fail").forward(request, response);
                }
            }
        } else if (ope.equals("notice")) {
            /**
             * NoticeRegist
             */
            CommunityDao communityDao = new CommunityDao();
            NoticeDao noticeDao = new NoticeDao();

            // [MODIFIED] 添加 null 和 empty 检查，防止 NumberFormatException
            String cidStr = request.getParameter("communityId");
            int cid = (cidStr != null && !cidStr.isEmpty()) ? Integer.parseInt(cidStr) : 0;

            int result = communityDao.getCommunityById(cid);
            if (result == 0) {
                request.getRequestDispatcher("admin/notice_add.jsp?rs=mNotIn").forward(request, response);
            } else {
                Notice notice = new Notice();

                // [MODIFIED] 添加 null 和 empty 检查，防止 NumberFormatException
                String noticeIdStr = request.getParameter("noticeId");
                notice.setNoticeId((noticeIdStr != null && !noticeIdStr.isEmpty()) ? Integer.parseInt(noticeIdStr) : 0);

                notice.setNoticeName(request.getParameter("noticeName"));
                notice.setNoticeIntroduction(request.getParameter("noticeIntroduction"));
                notice.setNoticeTime(request.getParameter("noticeTime"));

                // [MODIFIED] 使用已经检查过的 cid 变量
                notice.setCommunityId(cid);

//           notice.setCommunityName(request.getParameter("community_name"));
                String judge = noticeDao.addAdminNotice(notice);
                System.out.println(notice);
                if (judge.equals("success")) {
                    System.out.println("创建成功");
                    request.getRequestDispatcher("admin/notice_add.jsp?rs=success").forward(request, response);
                } else if (judge.equals("exist")) {
                    request.getRequestDispatcher("admin/notice_add.jsp?rs=exist").forward(request, response);
                } else {
                    request.getRequestDispatcher("admin/notice_add.jsp?rs=fail").forward(request, response);
                }
            }
        }else if (ope.equals("apply")) {
            /**
             * ApplyRegist
             */
            ApplyDao applyDao = new ApplyDao();
            String cname = request.getParameter("community_name");
            //System.out.println(id);
            //System.out.println("select"+cname);
            int cid = applyDao.getCommunityIdByCName(cname);
            //System.out.println("back"+cid);

            if (cid == 0) {
                request.getRequestDispatcher("admin/userapply.jsp?rs=mNotIn").forward(request, response);
            } else {
                Apply apply = new Apply();
                apply.setLoginName(request.getParameter("loginName"));
                apply.setMember_name(request.getParameter("member_name"));
                apply.setMember_gender(request.getParameter("member_gender"));
                apply.setMember_grade(request.getParameter("member_grade"));
                apply.setMember_institute(request.getParameter("memberInstitute"));
                apply.setCommunity_name(request.getParameter(cname));
                apply.setCommunityId(cid);

                String judge = applyDao.add(apply);

                if (judge.equals("success")) {
                    System.out.println("创建成功");
                    request.getRequestDispatcher("admin/userapply.jsp?rs=successful").forward(request, response);
                } else {
                    request.getRequestDispatcher("admin/userapply.jsp?rs=faile").forward(request, response);
                }
            }
        }

    }

}